import { defineBoot } from "#q-app/wrappers";
import common from "_s/common/localstore";
import { asyncRouter, constantRouter } from "_s/router/routes";
import { userInfo } from "../config/user/index";
import { Notify } from "quasar";
import { useUserHook } from "_s/stores/modules/user";
const { setUserInfo } = useUserHook();

import { useMenuHook } from "_s/stores/modules/menu";
const { setRouter } = useMenuHook();
import type { RouteRecordRaw } from "vue-router";

const homePage = "/";

const setAccessMenu = (roleMenu: string[], asyncRouter: RouteRecordRaw[]): RouteRecordRaw[] => {
  const res = [] as RouteRecordRaw[];
  asyncRouter.forEach(item => {
    const { meta, children } = item;
    if (meta?.id && roleMenu.includes(meta.id)) {
      if (children && children.length > 0) {
        item.children = setAccessMenu(roleMenu, children);
      }
      res.push(item);
    }
  });
  return res;
};

export default defineBoot(({ app, router }) => {
  console.log(app);
  router.beforeEach(async (to, from, next) => {
    console.log(to);
    const token = common.getToken();

    if (!token && to.path != "/login") {
      return next({
        path: "/login"
      });
    }

    if (!token && to.path == "/login") {
      return next();
    }

    if (token && to.path == "/login") {
      return next({
        path: homePage
      });
    }
    if (to.path == "/limit") {
      return next();
    }
    console.log(to);

    // if (isRouterReady) {
    //   // 路由已经准备好
    //   return next();
    // }

    try {
      // 权限判断
      const { code, data, msg } = await userInfo();

      if (code == -1 && !data) {
        // 用户在使用中被删除
        Notify.create({ type: "error", message: msg });
        return next({
          path: "/login"
        });
      }
      console.log(router.getRoutes());
      // 用户存在
      setUserInfo(data);
      const { auth } = data;
      const isAdmin = auth == 0;
      const roleMenu = ["user", "user_list", "test", "test_test1"];
      const accessRoutes = !isAdmin ? asyncRouter : setAccessMenu(roleMenu, asyncRouter);
      const menuRouter = constantRouter.concat(accessRoutes);
      setRouter(menuRouter); // 保存路由设置菜单
      // 重置路由
      router.getRoutes().forEach(item => {
        const name = item.name;
        if (name && !constantRouter.some(cRoute => cRoute.name === name)) {
          router.removeRoute(name);
        }
      });

      accessRoutes.forEach(route => {
        if (route.name && !router.hasRoute(route.name)) {
          router.addRoute(route);
        }
      });

      console.log(to);

      router.addRoute({
        path: "/:pathMatch(.*)*",
        name: "404",
        component: () => import("_p/404.vue"),
        meta: {
          hidden: true
        }
      });

      const routers = router.getRoutes();
      console.log(routers);
      const findRouter = routers.find(item => item.path == to.fullPath);

      if (to.matched.length == 0 && !findRouter) {
        next({ ...to, replace: true }); // 这里相当于push到一个页面 不在进入路由拦截
      } else {
        next();
      }
      // if (routers.find(item => item.path == to.fullPath)) {

      // } else {
      //   next({ ...to, replace: true }); // 这里相当于push到一个页面 不在进入路由拦截
      // }
    } catch {
      next({
        path: homePage
      }); // 这里相当于push到一个页面 不在进入路由拦截
    }

    // 用户权限处理
  });
});
